package com.gl.basis.zuul.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gl.basis.auth.constants.AuthorityConstants;
import com.gl.basis.common.constant.ResultCode;
import com.gl.basis.common.pojo.CommBean;
import com.gl.basis.common.pojo.CommonResult;
import com.gl.basis.common.util.IdWorker;
import com.gl.basis.common.util.NetworkUtil;
import com.gl.basis.zuul.entity.SysAppLog;
import com.gl.basis.zuul.entity.SysAppMapping;
import com.gl.basis.zuul.enums.RouteType;
import com.gl.basis.zuul.service.ISysAppLogService;
import com.gl.basis.zuul.service.ISysAppMappingService;
import com.gl.basis.zuul.util.RequestUtils;
import com.google.gson.JsonObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 根据用户传递的标识来获取用户实际服务地址进行转发
 * 
 * @author xiehong
 *
 */
@Component
public class RoutingFilter extends ZuulFilter {

	private static final Logger logger = LoggerFactory.getLogger(RoutingFilter.class);

	@Resource
	public ISysAppMappingService sysAppMappingService;
	@Resource
	private ObjectMapper objectMapper;
	@Resource
	private ISysAppLogService sysAppLogService;
	

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 2;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
        String path = request.getServletPath();
        //包含api就不转发
		if (!currentContext.sendZuulResponse() || (StringUtils.isNotBlank(path)&& path.contains(RouteType.API.getCode()))) {
			return false;
		}
		return true;
	}

	@Override
	public Object run() throws ZuulException {

		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		String requestParams = RequestUtils.getRequestParams(currentContext, request);
		logger.info(">>>>>>请求参数："+requestParams);
		if (StringUtils.isBlank(requestParams)) {
			currentContext.setSendZuulResponse(false);
			HttpServletResponse response = currentContext.getResponse();
			response.setContentType("application/json;charset=UTF-8");
			try {
				currentContext
						.setResponseBody(objectMapper.writeValueAsString(CommonResult.failed(ResultCode.GATEWAY_ERROR)));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		CommBean reqParams = JSONObject.parseObject(requestParams, CommBean.class);
		sysAppLogService.addLog(reqParams,request);
		
		if (reqParams == null || StringUtils.isBlank(reqParams.getMethod())) {
			currentContext.setSendZuulResponse(false);
			HttpServletResponse response = currentContext.getResponse();
			response.setContentType(AuthorityConstants.APPLICATION_JSON);
			try {
				currentContext
						.setResponseBody(objectMapper.writeValueAsString(CommonResult.failed(ResultCode.GATEWAY_ERROR)));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		
		SysAppMapping mappingUrl = sysAppMappingService.findAppMappingUrl(reqParams.getMethod());
		
		try {
			if (null != mappingUrl) {
				// 通过数据库查询
				String serviceId = mappingUrl.getServiceId();
				String insideApiUrl = mappingUrl.getInsideApiUrl();
				// 取出所有参数
				Enumeration<String> parameterNames = request.getParameterNames();
				while (parameterNames.hasMoreElements()) {
					String param = parameterNames.nextElement();
					insideApiUrl = insideApiUrl.replace("{" + param + "}", request.getParameter(param));
				}

				currentContext.put(FilterConstants.PROXY_KEY, serviceId);
				currentContext.put(FilterConstants.SERVICE_ID_KEY, serviceId);
				currentContext.put(FilterConstants.REQUEST_URI_KEY, insideApiUrl);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("服务异常：{}", e);
		}
		currentContext.setSendZuulResponse(false);
		HttpServletResponse response = currentContext.getResponse();
		response.setContentType("application/json;charset=UTF-8");
		try {
			currentContext
					.setResponseBody(objectMapper.writeValueAsString(CommonResult.failed(ResultCode.GATEWAY_ERROR)));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		return null;
	}

}
